package com.kpmg.questionnaire.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Locale;
import java.util.Map;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * 
 * @author Hanks
 *
 */
public class FreemarkerUtils {

	// 获取要写入PDF的内容
	public static String parseTemplate(String ftlPath, String ftlName, Map<String, Object> paramMap)
			throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException,
			TemplateException {
		return useTemplate(ftlPath, ftlName, paramMap);
	}

	// 使用freemarker得到html内容
	@SuppressWarnings("deprecation")
	public static String useTemplate(String ftlPath, String ftlName, Map<String, Object> paramMap)
			throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException,
			TemplateException {
		String html = null;
		Template tpl = getFreemarkerConfig(ftlPath).getTemplate(ftlName);
		tpl.setEncoding("UTF-8");
		StringWriter writer = new StringWriter();
		tpl.process(paramMap, writer);
		writer.flush();
		html = writer.toString();
		return html;
	}

	/**
	 * 获取Freemarker配置
	 * 
	 * @param templatePath
	 * @return
	 * @throws IOException
	 */
	private static Configuration getFreemarkerConfig(String templatePath) throws IOException {
		Configuration config = new Configuration(Configuration.VERSION_2_3_0);
		config.setDirectoryForTemplateLoading(new File(templatePath));
		config.setEncoding(Locale.CHINA, "utf-8");
		return config;
	}
}